<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-table :data="rolesList" border stripe>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :class="['bdbottom',i1===0? 'bdtop':'']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
            <el-col span="5">
              <el-tag>{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>

            <el-col span="19">
              <el-row v-for="(item2,i2) in item1.children" :key="item2.id">
                <el-col span="6">
                  <el-tag type="success">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col span="18">
                  <el-col>
                    <el-tag type="warning" v-for="(item3,i3) in item2.children"
                      :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-col>
              </el-row>

            </el-col>
          </el-row>


          <!-- <pre>{{ scope.row}}</pre> -->
        </template>
      </el-table-column>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描术" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button size='mini' type="primary" icon="el-icon-edit" @click="editRoles(scope.row)">编辑</el-button>
          <el-button size='mini' type="danger" icon="el-icon-delete" @click="removeRole(scope.row.id)">删除</el-button>
          <el-button size='mini' type="warning" icon="el-icon-setting"
            @click="showSetRightDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key='id' default-expand-all
        :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="增加角色" :visible.sync="addRolesDialogVisible" width="30%">
      <el-input v-model="roleInfo.roleName" placeholder="请输入角色名"></el-input>
      <el-input v-model="roleInfo.roleDesc" placeholder="请输入角色描术"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="saveRoles">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑角色" :visible.sync="editRolesDialogVisible" width="30%">
      <el-input v-model="roleInfo.roleName" placeholder="请输入角色名称"></el-input>
      <el-input v-model="roleInfo.roleDesc" placeholder="请输入角色描述"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditRoles">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      return {
        roleInfo: {
          roleId: '',
          roleName: '',
          roleDesc: ''
        },
        addRolesDialogVisible: false,
        editRolesDialogVisible: false,
        rolesList: [],
        rightsList: [],
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        defKeys: [],
        setRightDialogVisible: false,
      }
    },
    created() {
      this.getRolesList()
    },
    
    methods: {
      async saveRoles() {
        const {data: res} = await this.$http.post('roles', {
          roleName: this.roleName,
          roleDesc: this.roleDesc
        })
        if (res.meta.status !== 201) {
          return this.$message.error('创建角色失败')
        }
        this.$message.success('创建角色成功!')
        this.getRolesList()
        this.addRolesDialogVisible = false
        // console.log(res)
      },
      addRoles() {
        this.addRolesDialogVisible = true
      },
      async removeRole(id) {
        console.log(id)
        // console.log(id)
        const confirmResult = await this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
        const {
          data: res
        } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除角色失败!')
        }
        this.$message.success('删除角色成功!')
        this.getRolesList()
        console.log(res)

      },

      editRoles(roleInfo) {
        //roleName roleDesc 相同，直接整体赋值，id不同需单独赋值
        this.roleInfo = roleInfo
        this.roleInfo.roleId = roleInfo.id
        this.editRolesDialogVisible = true

        console.log(this.roleInfo.roleName);
      },

      async saveEditRoles() {
        console.log(this.roleInfo.roleId);
        const {
          data: res
        } = await this.$http.put(`roles/${this.roleInfo.roleId}`, {
          roleName: this.roleInfo.roleName,
          roleDesc: this.roleInfo.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色失败!')
        }
        this.$message.success('更新角色成功')
        this.getRolesList()
        this.editRolesDialogVisible = false
      },

      async getRolesList() {
        const {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          this.$message.error('获取失败！')
        }
        // console.log(res);
        this.rolesList = res.data
        console.log(this.rolesList);
      },

      async showSetRightDialog(role) {
        this.roleId = role.id
        const {
          data: res
        } = await this.$http.get('rights/tree')
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('获取权限列表失败')
        }
        this.$message.success('获取权限列表成功')
        this.rightsList = res.data
        this.getLeafKeys(role, this.defKeys)
        this.setRightDialogVisible = true
        console.log(this.rightsList);
      },

      getLeafKeys(node, arr) {
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      setRightDialogClosed() {
        this.defKeys = []
      },
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys(),
        ]
        const idStr = keys.join(',')
        console.log(idStr)
        const {
          data: res
        } = await this.$http.post(`roles/${this.roleId}/rights`, {
          rids: idStr
        })
        if (res.meta.status !== 200) {
          return this.$message.error('分配权限失败')
        }
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.setRightDialogVisible = false
        console.log(res);

      }
    }

  }
</script>

<style lang="less" scoped>
  .el-input {
    margin: 10px;
  }

  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }
</style>
